package applogic

import (
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"

	"auto/logger"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var (
	appws = websocket.Upgrader{
		ReadBufferSize:   1024,
		WriteBufferSize:  1024,
		CheckOrigin:      func(r *http.Request) bool { return true },
		HandshakeTimeout: time.Second * 10,
	}
	AppWsConn WsConn
)

type WsConn struct {
	*websocket.Conn
	Mux sync.RWMutex
	WsData
}

type WsData struct {
	Type    string         `json:"type"`
	Message map[string]any `json:"message"`
}

func WsAppapi(c *gin.Context) {
	var err error
	AppWsConn.Conn, err = appws.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println("不能更新连接:", err)
		return
	}
	defer func(ws *websocket.Conn) {
		err := ws.Close()
		if err != nil {
			fmt.Println(err)
		}
	}(AppWsConn.Conn)

	var context WsData
	for {

		//读取ws中的数据
		err := AppWsConn.ReadJSON(&context)
		if err != nil {
			logger.Error("WS读取失败--->", err)
			_ = AppWsConn.WriteJSON(map[string]any{"msg": "数据解析失败"})
			return
		}
		switch context.Type {
		case "download": // 获取本地播放列表
			// {"filename":"第一集","m3url":"https://xxx.m3u8","name":"荒野求生"}
			filename := context.Message["filename"]
			m3url := context.Message["m3url"]
			name := context.Message["name"]
			//写入ws数据
			fmt.Println(name, m3url)
			//time.Sleep(3 * time.Second)
			err = AppWsConn.WriteJSON(map[string]any{"download": filename})
			if err != nil {
				break
			}

		default:
			_ = AppWsConn.WriteJSON(map[string]any{"msg": "没有这个功能"})
		}

	}
}
